﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Globalization;
using Zhao.Arena.Utility.InitDatabaseExt;
using Zhao.Common.EnumEntity;
using Zhao.Common.Helper;
using Zhao.IServer.Field;
using Zhao.IServer.Management_Arena;
using Zhao.Models.DTO;
using Zhao.Models.Entity;

namespace Zhao.Arena.Controllers.Field
{
    /// <summary>
    /// 场地预约
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [Function("场地预约", null, "booking", "../views/Home/booking/index.vue")]
    [Authorize]
    public class AppointmentsController : ControllerBase
    {
        private readonly IMapper _mapper;
        private readonly IFieldTypesServer _typeServer;
        private readonly IFieldsServer _fieldsServer;
        private readonly IVenuesServer _venuesServer;
        private readonly IAppointmentsServer _appointmentsServer;

        public AppointmentsController(IMapper mapper, IFieldTypesServer typeServer, IFieldsServer fieldsServer, IVenuesServer venuesServer, IAppointmentsServer appointmentsServer)
        {
            _mapper = mapper;
            _typeServer = typeServer;
            _fieldsServer = fieldsServer;
            _venuesServer = venuesServer;
            _appointmentsServer = appointmentsServer;
        }


        /// <summary>
        /// 预约场地
        /// </summary>
        /// <param name="reservation"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Reservation(ReservationDto reservation)
        {
            var result = new ApiResult() { Success = false, Message = "操作失败" };
            // 基础对象校验
            if (reservation == null)
            {
                result.Message = "预约信息不能为空";
                return new JsonResult(result);
            }

            // 用户信息校验
            if (reservation.userName.IsNullOrWhiteSpace())
            {
                result.Message = "用户姓名不能为空";
                return new JsonResult(result);
            }

            if (!reservation.phone.IsMobileNumber())
            {
                result.Message = "手机号码格式不正确";
                return new JsonResult(result);
            }

            // 日期格式校验
            if (!reservation.displayDate.IsValidIsoDate())
            {
                result.Message = "日期格式应为YYYY-MM-DD";
                return new JsonResult(result);
            }

            // DisplayDate必须>=当前日期
            if (DateTime.TryParseExact(reservation.displayDate, "yyyy-MM-dd",
                CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime displayDate))
            {
                if (displayDate.Date < DateTime.Today)
                {
                    result.Message = "预约日期不能早于当前日期";
                    return new JsonResult(result);
                }
            }

            // 价格校验
            if (reservation.totalPrice <= 0)
            {
                result.Message = "总价格必须大于0";
                return new JsonResult(result);
            }

            if (reservation.infos.Sum(s => s.Price) != reservation.totalPrice)
            {
                result.Message = "价格不一致";
                return new JsonResult(result);
            }

            // 场地信息校验
            if (reservation.infos == null || !reservation.infos.Any())
            {
                result.Message = "至少需要预约一个场地";
                return new JsonResult(result);
            }

            //对场地预约信息进行校验
            foreach (var info in reservation.infos)
            {
                // 场地ID校验
                if (info.fId <= 0)
                {
                    result.Message = "场地ID无效";
                    return new JsonResult(result);
                }

                // 时间有效性校验
                if (info.StartTime >= info.EndTime)
                {
                    result.Message = "开始时间必须早于结束时间";
                    return new JsonResult(result);
                }
            }

            //对操作的人员进行验证判断是否 是该球馆的管理员 不是该球馆的管理员不能对此球馆进行预约操作
            //这里能够拿到Userid ,说明token必然已经验证通过了 
            string? venueIdClaim = User.FindFirst("VenueId").Value;

            if (venueIdClaim == null || !Guid.TryParse(venueIdClaim, out Guid venueId))
            {
                result.Message = "对当前场地没有操作权限";
                return new JsonResult(result);
            }

            //如果验证都通过了传递给服务层 进行数据层面的查询
            //如果没问题就传递给服务层

            result = await _appointmentsServer.BookingAVenue(venueId, reservation);

            return new JsonResult(result);
        }

        /// <summary>
        /// 根据id获取一条预约数据
        /// </summary>
        /// <param name="aId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("{aId:int}")]
        public async Task<JsonResult> GetAppointmentInfo(int aId)
        {
            var result = new ApiResult() { Success = false, Message = "操作失败" };

            if (aId <= 0)
            {
                return new JsonResult(result);
            }

            //是否要做球馆id限制????
            //string? venueIdClaim = User.FindFirst("VenueId").Value;

            //if (venueIdClaim == null || !Guid.TryParse(venueIdClaim, out Guid venueId))
            //{
            //    result.Message = "对当前场地没有操作权限";
            //    return new JsonResult(result);
            //}

            result = await _appointmentsServer.GetAppointmentById(aId);

            return new JsonResult(result);
        }


        /// <summary>
        /// 修改订单状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        [HttpPut("{id}/status/{newStatus}")]
        public async Task<JsonResult> UpdateAppointmentStatus(int id, short newStatus)
        {
            var result = new ApiResult() { Success = false, Message = "操作失败" };

            var info = await _appointmentsServer.QueryAsync(x => x.AppointmentID == id);

            if (info == null)
            {
                result.Message = "未查询订单";
                return new JsonResult(result);
            }

            if (newStatus == (short)AppointmentStatus.Completed)
            {

                DateTime currentTime = DateTime.Now;
                // 假设 info.DisplayDate = "2025-04-16"，info.EndTime = 2025-04-16 14:30:45
                DateTime displayDate = DateTime.Parse(info.DisplayDate); // 解析字符串日期
                TimeSpan timeOfDay = info.EndTime.TimeOfDay; // 提取时间部分

                DateTime combinedDateTime = displayDate.Date + timeOfDay;

                if (currentTime < combinedDateTime)
                {
                    result.Message = "当前时间未达到预约结束时间，无法修改订单状态";
                    return new JsonResult(result);
                }
            }



            //如果和库中的状态一样 直接返回就行
            if (info.Status == newStatus)
            {
                result.Success = true;
                result.Message = "操作成功";
                return new JsonResult(result);
            }

            result = await _appointmentsServer.UpdateAppointmentStatus(id, newStatus);

            return new JsonResult(result);
        }

        /// <summary>
        /// 取消场地预约
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>

        [HttpPost("{id}/cancel")]
        public async Task<IActionResult> Cancel([FromRoute] int id)
        {
            // 专属取消逻辑
            //是否要添加开场前多少分钟不能取消预定

            var result = new ApiResult() { Success = false, Message = "操作失败" };

            var info = await _appointmentsServer.QueryAsync(x => x.AppointmentID == id);

            //现在的时间
            DateTime currentTime = DateTime.Now;

            //
            if (currentTime >= info.StartTime)
            {
                result.Message = "当前订单已开始暂不支持取消";
                return new JsonResult(result);
            }

            return new JsonResult(await _appointmentsServer.CancelAppointment(id));
        }


        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="searchaString"></param>
        /// <param name="typeid"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("{pageIndex:int}/{pageSize:int}")]
        [Route("{pageIndex:int}/{pageSize:int}/{searchaString}/{displayDate}/{stasus:int}")]
        [Function("预约订单", null, "site", "../views/Home/site/siteInfo/index.vue")]
        public async Task<JsonResult> GetAppointmentsPage(int pageIndex = 1, int pageSize = 10, string searchaString = " ", short stasus = 99, string displayDate = " ")
        {

            var result = new ApiResult<PageModel<AppointmentsDto>>
            {
                Success = false,
                Message = "未查询到数据"
            };

            //只获取对应球馆id的预约信息
            Expressionable<Appointments, Fields> expressionable = new Expressionable<Appointments, Fields>();

            //如果是管理员的话就展示所有的预约订单
            string? venueIdClaim = User.FindFirst("VenueId").Value;

            Guid.TryParse(venueIdClaim, out Guid venueId);

            if (venueId != default)
            {
                expressionable.And((a, b) => a.VenueID.Equals(venueIdClaim));
            }

            expressionable.AndIF(!searchaString.IsNullOrWhiteSpace(), (a, b) => a.Mobile.Contains(searchaString) ||
              a.Name.Contains(searchaString));

            expressionable.AndIF(!displayDate.IsNullOrWhiteSpace(), (a, b) => a.DisplayDate.Equals(displayDate));

            expressionable.AndIF(stasus != 99, (a, b) => a.Status.Equals(stasus));

            result.Data = await _appointmentsServer.GetInfos(expressionable, pageIndex, pageSize);

            if (result.Data != null)
            {
                result.Success = true;
                result.Message = "操作成功";
            }

            return new JsonResult(result);
        }
    }
}
